<template>
  <HeaderTitle title="员工签收报表"></HeaderTitle>
  <div class="deliveryReportPage">
    <div class="row searchBox">
      <div class="sbTitle">金成色选项</div>
      <div class="gtBox">
        <div v-for="(gold, index) in goldTypeInfo" :key="index" class="row">
          <div class="col-10 gtTitle" :class="{ goldChosen: gold.isChosen }">
            {{ gold.goldType }}
          </div>
          <div class="col-2 gtBtn" @click="toggleChoice(index)">
            <q-icon name="fa-solid fa-check" color="white" class="gtSVG" />
          </div>
        </div>
      </div>
      <div class="row sbTitle">截数日期时间</div>
      <div class="row dateRangeBox items-center">
        <div class="col">
          <q-select
            color="deep-purple-9"
            bg-color="white"
            popup-content-style="font-size: 1rem;"
            filled
            v-model="dateTime"
            :options="dateTimeChoice"
            dense
          >
            <template v-slot:prepend>
              <q-icon name="event" />
            </template>
          </q-select>
        </div>
      </div>
    </div>

    <div class="row searchBtnBox">
      <q-btn color="deep-purple-10" class="searchBtn" @click="searchInfo()"
        >搜寻</q-btn
      >
    </div>

    <div v-if="showResult" class="row resultBox">
      <div class="exportBtnBox">
        <q-btn
          color="blue-10"
          class="exportBtn"
          label="导出"
          @click="exportTable()"
        >
          <q-icon name="fa-solid fa-file-arrow-down" class="exportSVG" />
        </q-btn>
      </div>
      <q-table
        flat
        bordered
        dense
        separator="cell"
        table-header-class="bg-grey-4"
        :rows="rbrows"
        :columns="rbcolumns"
        row-key="NO"
        class="resultTable"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, toRaw } from "vue";
import { useUserStore } from "src/stores/modules/userStore";
import { useReportStore } from "src/stores/modules/reportStore";
import HeaderTitle from "src/components/HeaderTitle.vue";
import { formatDateTimeString } from "src/utils/dateUtils";
import { jsonParse } from "src/utils/utils";
import { useQuasar, Loading, exportFile } from "quasar";

import { exportWorkerReportResult} from 'src/services/reportService'


// Search Box Requirements
const dateTime = ref(null);
const dateFrom = ref(null);
const dateTo = ref(null);
// const dateTimeChoice = [
//   "B3T0098: 2022.09(2022.08.22) 15:42:43 ~2022.09.22 15:46:45",
//   "B3T0098: 2022.09(2022.08.22) 15:42:43 ~2022.09.22 15:46:46",
//   "B3T0098: 2022.09(2022.08.22) 15:42:43 ~2022.09.22 15:46:47",
// ];

const $q = useQuasar();

const dateTimeChoice = ref([]);
const goldTypeInfo = ref([]);
const showResult = ref(false);

const useUser = useUserStore();
const useReport = useReportStore();

let staffCode = null;
let userCode = null;
const reportType = "handover";

const init = async () => {
  // get user data:
  staffCode = useUser.staffID;
  userCode = useUser.currentDept.userCode;

  if (staffCode && userCode) {
    // call api // get params: goldtype, datetimechoice
    const res = await useReport.getWorkerReportParams(
      reportType,
      staffCode,
      userCode
    );
    if (res) {
      console.log(res); 
      const obj = res.goldNK.replace(/'/g, '"');
      const date_obj = res.workCutData.replace(/'/g, '"');
      const newobj = JSON.parse(obj.replace(/\\"/g, '"'));
      const new_date_obj = JSON.parse(date_obj.replace(/\\"/g, '"'));
      // console.log(newobj);
      // console.log(new_date_obj);
      const goldNkArray = newobj.data;
      const dateChoiceArray = new_date_obj.data;
      goldTypeInfo.value = [];

      console.log('goldNkArray', goldNkArray);
      console.log('dateChoiceArray', dateChoiceArray);
      for (let i = 0; i < goldNkArray.length; i++) {
        const { Nk, NkDesc } = goldNkArray[i];
        goldTypeInfo.value.push({
          goldType: `${Nk} (${NkDesc})`,
          isChosen: false,
          gold_type: `${Nk}`,
        });
      }
      dateTimeChoice.value = [];
      for (let choice of dateChoiceArray) {
        dateTimeChoice.value.push(
          `${choice.dptcde}: 从 ${formatDateTimeString(
            choice.dtFrom
          )} 至 ${formatDateTimeString(choice.dtTo)}`
        );
      }
    } else {
      // error msg

      console.log("3", res);
    }
  }
};
init();

// Result Table
const rbcolumns = [
// {
//     name: "NO",
//     required: true,
//     label: "序号",
//     align: "left",
//     field: "RowID",
//     format: (val) => `${val}`,
//     sortable: true,
//   },
  {
    name: "dept",
    align: "center",
    label: "工人部门",
    field: "dptcde",
    sortable: true,
  },
  {
    name: "Crtdate",
    align: "center",
    label: "Crtdate",
    field: "Crtdate",
    sortable: true,
  },
  {
    name: "orderNo",
    align: "center",
    label: "生产单号",
    field: "Sonum",
    sortable: true,
  },
  {
    name: "moldNo",
    align: "center",
    label: "designnum",
    field: "designnum",
    sortable: true,
  },
  {
    name: "moldNo",
    align: "center",
    label: "designno",
    field: "designno",
    sortable: true,
  },
  {
    name: "goldType",
    align: "center",
    label: "金料成色",
    field: "stkcde",
    sortable: true,
  },
  {
    name: "qty",
    align: "center",
    label: "订单件数",
    field: "qty_order",
    sortable: true,
  },
  {
    name: "Qty_orderVhr",
    align: "center",
    label: "Qty_orderVhr",
    field: "Qty_orderVhr",
    sortable: true,
  },
  {
    name: "Remark2",
    align: "center",
    label: "Remark2",
    field: "Remark2",
    sortable: true,
  },
  {
    name: "StoneItm",
    align: "center",
    label: "StoneItm",
    field: "StoneItm",
    sortable: true,
  },
  {
    name: "TinQty",
    align: "center",
    label: "TinQty",
    field: "TinQty",
    sortable: true,
  },
  {
    name: "TotQty",
    align: "center",
    label: "TotQty",
    field: "TotQty",
    sortable: true,
  },
  {
    name: "AddGoldQty",
    align: "center",
    label: "AddGoldQty",
    field: "AddGoldQty",
    sortable: true,
  },
  {
    name: "FGStoneQty",
    align: "center",
    label: "FGStoneQty",
    field: "FGStoneQty",
    sortable: true,
  },
  {
    name: "NKDesc",
    align: "center",
    label: "NKDesc",
    field: "NKDesc",
    sortable: true,
  },
  {
    name: "Noitm_order",
    align: "center",
    label: "Noitm_order",
    field: "Noitm_order",
    sortable: true,
  },
  {
    name: "Scrape",
    align: "center",
    label: "Scrape",
    field: "Scrape",
    sortable: true,
  },
  {
    name: "Unit_cost",
    align: "center",
    label: "Unit_cost",
    field: "Unit_cost",
    sortable: true,
  },
  {
    name: "Var_tax",
    align: "center",
    label: "Var_tax",
    field: "Var_tax",
    sortable: true,
  },
  {
    name: "method",
    align: "center",
    label: "method",
    field: "method",
    sortable: true,
  },
  {
    name: "vhrnum",
    align: "center",
    label: "vhrnum",
    field: "vhrnum",
    sortable: true,
  },

]
// const rbcolumns = [
//   {
//     name: "NO",
//     required: true,
//     label: "序号",
//     align: "left",
//     field: (row) => row.no,
//     format: (val) => `${val}`,
//     sortable: true,
//   },
//   {
//     name: "date",
//     align: "center",
//     label: "日期",
//     field: "date",
//     sortable: true,
//   },
//   {
//     name: "orderNo",
//     align: "center",
//     label: "生产单号",
//     field: "orderNo",
//     sortable: true,
//   },
//   {
//     name: "qty",
//     align: "center",
//     label: "订单件数",
//     field: "qty",
//     sortable: true,
//   },
//   {
//     name: "designNo",
//     align: "center",
//     label: "设计编号",
//     field: "designNo",
//     sortable: true,
//   },
//   {
//     name: "goldType",
//     align: "center",
//     label: "金料成色",
//     field: "goldType",
//     sortable: true,
//   },
//   {
//     name: "sendGoldWeight",
//     align: "center",
//     label: "发料金重",
//     field: "sendGoldWeight",
//     sortable: true,
//   },
//   {
//     name: "receiveGoldWeight",
//     align: "center",
//     label: "实收金重",
//     field: "receiveGoldWeight",
//     sortable: true,
//   },
//   {
//     name: "loseMoney",
//     align: "center",
//     label: "亏赚金",
//     field: "loseMoney",
//     sortable: true,
//   },
//   {
//     name: "consumpPercentage",
//     align: "center",
//     label: "给耗百分比(%)",
//     field: "consumpPercentage",
//     sortable: true,
//   },
//   {
//     name: "difference",
//     align: "center",
//     label: "磅差或给耗",
//     field: "difference",
//     sortable: false,
//   },
// ];

// HARDCODE
const rbrows = ref([
// {
//   'RowID': 'RowID',
//   'designno': 'designno',
//   'fgwgt': 'fgwgt',
//   'in_fgwgt': 'in_fgwgt',
//   'out_fgwgt': 'out_fgwgt',
//   'in_date': 'in_date',
//   'out_date': 'out_date',
//   'qty': 'qty',
//   'scrap': 'scrap',
//   'sonum': 'sonum',
//   'stkcde': 'stkcde',
//   'stoneqty': 'stoneqty',
//   'stonewgt': 'stonewgt',
//   'wrkdpt': 'wrkdpt',
// }
]);

// Function: Toggle goldType choices
const toggleChoice = (idx) => {
  for(let i = 0; i<goldTypeInfo.value.length; i++){
    if(i==idx){
      goldTypeInfo.value[i].isChosen = true
    }else{
      goldTypeInfo.value[i].isChosen = false
    }
  }
};

// Function: search
const searchInfo = async () => {
  // get search req
  let goldItems = goldTypeInfo.value.filter((g) => g.isChosen);
  goldItems = toRaw(goldItems);
  console.log("goldItems: ", goldItems);
  console.log("dateTime: ", dateTime.value);
  // call api
  const goldType = goldItems;

  if (dateTime.value) {
    const date = dateTime.value.split("从");

    const formatDate = date[1].split("至");
    dateFrom.value = formatDate[0].trim().split(" ").join("T");
    dateTo.value = formatDate[1].trim().split(" ").join("T");
    // console.log(dateFrom.value);
    // console.log(dateTo.value);
  }

  rbrows.value = []
  if (goldType.length > 0) {
    let goldArr = [];
    for (let item of goldItems) {
      goldArr.push(item.gold_type)
    }
    
    // staffCode = '10001274'
    // userCode = 'F3F1274'
    // dateFrom.value = '2023-01-10T00:00:00'
    // dateTo.value = '2023-01-11T00:00:00'
    const goldType = goldArr.join();
    
    const res = await useReport.getWorkerReportResult(
      reportType,
      staffCode,
      userCode,
      goldType,
      dateFrom.value,
      dateTo.value
    );
    console.log(res.data);
    if (res.data.data){
      // console.log(res.data.data);
      const test = res.data.data.replace(/\\"/g,'"')
      // console.log(test);
      const testjson = JSON.parse(test)
      console.log(testjson);

      // const json = jsonParse(res.data.data)
      // console.log('WorkerTrx',json.data.WorkerTrx);
      
      rbrows.value = [...rbrows.value, ...testjson.data]

    }
    showResult.value = true
  }
  showResult.value = true

};



const exportTable = async () => {

  
console.log("downloading worker handset file... ");
  // get search req
  let goldItems = goldTypeInfo.value.filter((g) => g.isChosen);
  goldItems = toRaw(goldItems);
  console.log("goldItems: ", goldItems);
  console.log("dateTime: ", dateTime.value);
  // call api
  const goldType = goldItems;

  if (dateTime.value) {
    const date = dateTime.value.split("从");

    const formatDate = date[1].split("至");
    dateFrom.value = formatDate[0].trim().split(" ").join("T");
    dateTo.value = formatDate[1].trim().split(" ").join("T");
    // console.log(dateFrom.value);
    // console.log(dateTo.value);
  }

  // rbrows.value = []
  if (goldType.length > 0) {
    let goldArr = [];
    for (let item of goldItems) {
      goldArr.push(item.gold_type)
    }
    
    // staffCode = '10001274'
    // userCode = 'F3F1274'
    // dateFrom.value = '2023-01-10T00:00:00'
    // dateTo.value = '2023-01-11T00:00:00'
    const goldType = goldArr.join();
    try {
      Loading.show()
      console.log("call API")
      const res = await exportWorkerReportResult(
        reportType,
        staffCode,
        userCode,
        goldType,
        dateFrom.value,
        dateTo.value
      );
      if (res.status==200){
        const filename = "workerHandover.csv"
        // const filename = res.headers['content-disposition'].split('filename=')[1].replace(/"/g, '');

        const status = exportFile(filename, res.data, {
        encoding: 'utf-8',
        mimeType: 'text/csv;',
        byteOrderMark: '\uFEFF'
      })

      if (status!=true){
        $q.notify({
          message: '导出失败',
          color: 'negative',
          timeout: 2000,
          position: "center",
        })
      }else{
        $q.notify({
          message: '导出成功',
          color: 'positive',
          timeout: 2000,
          position: "center",
        })
      }

      }
    } catch (error) {
      console.log(error);
    }
    Loading.hide()

}


}


</script>

<style lang="scss">
.deliveryReportPage {
  width: 90%;
  margin-left: auto;
  margin-right: auto;
  font-size: 1rem;
  @media (max-width: 480px) {
    font-size: 1rem;
  }

  .searchBox {
    margin-top: 20px;
    border-radius: 10px;
    padding: 5px 10px 10px 10px;
    width: 100%;
    background-color: rgba(255, 255, 255, 0.829);
    .sbTitle {
      width: 100%;
      font-weight: bold;
      margin-bottom: 5px;
      margin-top: 10px;
    }
    .gtBox {
      width: 100%;
      text-align: center;
      margin-top: 3px;
      .gtTitle {
        background-color: white;
        margin-top: 3px; // This will be deleted when choices box is in v-for
      }
      .gtBtn {
        background-color: #6456c8;
        margin-top: 3px; // This will be deleted when choices box is in v-for
      }
      .goldChosen {
        background-color: #b8aeff !important;
      }
    }
    .dateRangeBox {
      width: 100%;
      text-align: center;
      .drContent {
        margin-right: 5px;
        margin-left: 5px;
      }
    }
  }

  .searchBtnBox {
    margin-top: 15px;
    width: 100%;
    .searchBtn {
      width: 100%;
    }
  }

  .resultBox {
    margin-top: 10px;
    width: 100%;
    .exportBtnBox {
      margin-left: 10px;
      text-align: right;
      width: 100%;
      .exportBtn {
        font-size: 1rem;
        .exportSVG {
          margin-left: 5px;
        }
      }
    }
    .resultTable {
      width: 100%;
      margin-top: 10px;
    }
  }
}
</style>
